// pages/sales/boss_ai/index.js
import * as echarts from '../ec-canvas/echarts';
var cf = require("../../../config.js");
var util = require("../../../utils/util.js");
var cusmallToken = wx.getStorageSync('cusmallToken');
var baseHandle = require("../../template/baseHandle.js"); 
var app = getApp();
Page(Object.assign({}, baseHandle,{

  /**
   * 页面的初始数据
   */
  data: {
    extConfig: wx.getExtConfigSync ? wx.getExtConfigSync() : {},
    app: app,
    staticResPath: cf.config.staticResPath,
    userImagePath: cf.config.userImagePath,
    salerName: "",
    salerList: [],
    focusSearchName:false,
    name: "全部",
    salerIsLoading: false,
    salerPage: 1,
    isSalerBottom: false,
    isScroll: false,
    activeName:"all",
    activeAllData:"all",
    list: [],
    isLoading: false,
    pageSize: 10,
    curPage: 1,
    isBottom: false,

    listStaff: [],
    isLoadingDepart: false,
    curPageDepart: 1,
    isBottomDepart: false,
    identify: "",//指定查询的部门 (需要员工拥有该部门的管理权限)
    totalStaff:0,
    reLoadStaffList:false,

    aiList: [],
    abList:[],//雷达图 数值
    aiIsLoading: false,
    aiCurPage: 1,
    aiIsBottom: false,
    rankType:1,
    allData:{
      memberCount:0,
      forwardNum:0,
      followNum:0,
      pv:0,
      saveNum:0,
      thumbsNum:0
    },
    swCur:0,
    ecInt: {
      // 将 lazyLoad 设为 true 后，需要手动初始化图表
      lazyLoad: true
    },
    interestData: {},
    pickNameInterest:"近7天",
    ecFunnel: {
      lazyLoad: true
    },
    dealData: {},
    pickNameDeal:"近7天",
    ecNewCust: {
      lazyLoad: true
    },
    newCustData: {},
    askCustData: {},
    followCustData: {},
    mallOrderData: {},
    pickerNameNewCust:"近7天",
    pickerNameAskCust:"近7天",
    pickerNameMallOrder:"近7天",
    pickerNameFollowCust:"近7天",
    ecActiveCust: {
      lazyLoad: true
    },
    ecActiveData:{},
    ecInteraction:{
      lazyLoad: true
    },
    ecInteractionData: {
      list: []
    },
    pickerArr: [
      {
        name: "近7天",
        key: "7",
      },
      {
        name: "近15天",
        key: "15",
      },
      {
        name: "近30天",
        key: "30",
      }
    ],
    pickerName: "近7天",
    ecAi:{
      lazyLoad: true
    },
    abilityData:{},

    empManageEnable:false,
    createCardEnable:false,
    restCard:0,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    wx.hideShareMenu();
    var ctx = this;
    this.interestComponent = this.selectComponent('#mychart-dom-pie');
    this.dealComponent = this.selectComponent('#mychart-dom-funnel');
    this.newCustComponent = this.selectComponent('#mychart-new-cust');
    this.askCustComponent = this.selectComponent('#mychart-ask-cust');
    this.followCustComponent = this.selectComponent('#mychart-follow-cust');
    this.mallComponent = this.selectComponent('#mychart-mall');
    this.activeCustComponent = this.selectComponent('#mychart-active-cust');
    this.interactionComponent = this.selectComponent('#mychart-interaction');
    // ctx.activeComponent = ctx.selectComponent('#mychart-dom-line');
    // ctx.interactionComponent = ctx.selectComponent('#mychart-dom-bar');
    app.getUserInfo(ctx, options, function (userInfo, res) {
      cusmallToken = wx.getStorageSync('cusmallToken');
      ctx.findEmployeePrivilege();
      ctx.queryBossData("all");

      ctx.queryCustomerRank(ctx.data.rankType);
      ctx.queryAi();
      ctx.interest(7);
      ctx.dealPer(7);
      ctx.newCust(7);
      ctx.askCust(7);
      ctx.mallOrder(7);
      ctx.followCust(7);
      ctx.otherCharts();
      ctx.activeCust(7);
      ctx.interaction();
    });
  
  },
  
  changeInput(e) {
	  this.setData({
		 salerName: e.detail.value
	  });
  },
  searchSales() {
	var ctx = this;
	ctx.setData({
	   activeName: "search"
    });
    if (ctx.data.salerIsLoading) {
       return;
    } else if (ctx.data.isScroll && ctx.data.isSalerBottom) {
       ctx.data.isScroll= !(ctx.data.isScroll);
       return;
    }
    if (ctx.data.isScroll) {
    	ctx.setData({ 
    		salerPage: ctx.data.salerPage + 1
    	});
    } else {
    	ctx.setData({ 
    		salerPage: 1,
    		isSalerBottom: false
    	});
    }
    ctx.setData({ 
    	salerIsLoading: true
	});
    wx.request({
      url: cf.config.pageDomain + "/applet/mobile/visitcard/dataprofile/abilityList",
      data: {
        cusmallToken: cusmallToken,
        department: ctx.data.identify,
        name: ctx.data.salerName,
        start: (ctx.data.salerPage - 1) * 8,
        limit: 8,
      },
      header: {
        'content-type': 'application/json'
      },
      success: function (res) {
        var data = res.data;
        if (data && 0 === data.ret) {
          var list = data.model.employeeList || [];
          if (ctx.data.isScroll) {
        	  ctx.setData({
        		  salerList: ctx.data.salerList.concat(list),
        	  });
          } else {
        	  ctx.setData({
        		  salerList: list,
        	  });
          }
          if (data.model.total <= ctx.data.salerList.length) {
             ctx.setData({
               isSalerBottom: true
             });
          }
        } else {
          wx.showToast({
            title: data.msg,
            icon: "none"
          })
        }
      },
      fail() {
    	ctx.setData({ salerIsLoading: false });
      },
      complete() {
        ctx.setData({ salerIsLoading: false });
      }
    });
  },
  clearInput() {
	this.setData({
		salerName: "",
		activeName: "all"
	});  
  },
  changeTab(e){
    var tab = e.currentTarget.dataset.tab;
    var idx = e.currentTarget.dataset.idx;
    var ctx = this;
    ctx.setData({
      activeName: tab
    });
    if("ai"== tab){
      ctx.renderRadar();
    } else if ("all" == tab){
      ctx.interest(7);
      ctx.dealPer(7);
      ctx.newCust(7);
      ctx.askCust(7);
      ctx.mallOrder(7);
      ctx.followCust(7);
      ctx.otherCharts();
      ctx.activeCust(7);
      ctx.interaction();
    }
  },
  selectRankType(e){
    var type = e.currentTarget.dataset.type;
    var ctx = this;
    ctx.setData({
      rankType: parseInt(type),
      isLoading:false,
      list:[],
      isBottom:false,
      curPage:1 
    })
    ctx.queryCustomerRank(parseInt(type));

  },
  swChange(e){
    var ctx = this;
    ctx.setData({
      allData:{
        memberCount:0,
        followNum:0,
        pv:0,
        forwardNum:0,
        saveNum:0,
        thumbsNum:0
      }
    });
    var cur = e.detail.current;
    switch (cur){
      case 0:
        cur = "all";
      break;
      case 2:
        cur = 7;
      break;
      case 3:
        cur = 30;
      break;
    }
    ctx.setData({
      activeAllData: cur
    })
    ctx.queryBossData(cur);
    console.log(e)
  },
  changeAllData(e){
    var day = e.currentTarget.dataset.day;
    var ctx = this;
    switch (day) {
      case "all":
        ctx.setData({
          swCur:0
        });
        break;
      case "1":
        ctx.setData({
          swCur: 1
        });
        break;
      case "7":
        ctx.setData({
          swCur: 2
        });
        break;
      case "30":
        ctx.setData({
          swCur: 3
        });
        break;
    }
    ctx.setData({
      activeAllData: day
    })
    // ctx.queryBossData(day);
  },
  queryBossData(day){// all simple data
    var ctx = this;
    var endDate = "", startDate="";
    if("all" != day){
      if(1 == day){
        endDate = util.formatDate(new Date(Date.now() - (day * 86400000)));
      }else{

        endDate = util.formatDate(new Date());
      }
      startDate = util.formatDate(new Date(Date.now() - (day * 86400000)));
    }
    
    wx.request({
      url: cf.config.pageDomain + "/applet/mobile/visitcard/dataprofile/bossData",
      data: {
        cusmallToken: cusmallToken,
        startDate: startDate,
        endDate: endDate,
        department: ctx.data.identify
        // department:""
      },
      header: {
        'content-type': 'application/json'
      },
      success: function (res) {
        var data = res.data;
        if (data && 0 === data.ret) {
          ctx.setData({
            allData:data.model
          })
        } else {
          wx.showToast({
            title: data.msg,
            icon: "none"
          })
        }
      },
      fail() {

      },
      complete() {
      }
    });
  },
  queryCustomerRank(type){// sale rank
    var ctx = this;
    if (ctx.data.isLoading || ctx.data.isBottom) {
      return;
    }
    ctx.setData({ isLoading: true });
    wx.showLoading({
      title: '加载中...'
    })
    wx.request({
      url: cf.config.pageDomain + "/applet/mobile/visitcard/dataprofile/customerRank",
      data: {
        cusmallToken: cusmallToken,
        start: (ctx.data.curPage - 1) * ctx.data.pageSize,
        department: ctx.data.identify,
        limit: ctx.data.pageSize,
        type:type
      },
      header: {
        'content-type': 'application/json'
      },
      success: function (res) {
        var data = res.data;
        if (data && 0 === data.ret) {
          var list = data.model.employeeList || [];
          ctx.setData({
            list: ctx.data.list.concat(list),
          });
          if (data.model.total == ctx.data.list.length) {
            ctx.setData({
              isBottom: true
            });
          }
        } else {
          wx.showToast({
            title: data.msg,
            icon: "none"
          })
        }
      },
      fail() {

      },
      complete() {
        wx.hideLoading();
        ctx.setData({ isLoading: false });
      }
    });
  },
  focusSearchName:function(){
    this.setData({
      focusSearchName:true
    })
  },
  cancelSearchName:function(){
    this.setData({
      salerName: "",
      activeName: "all",
      focusSearchName:false
    });
  },
  selDepartmentCallback: function (depart){
    this.setData({
      salerName: "",
      salerList: [],
      focusSearchName: false,
      salerIsLoading: false,
      salerPage: 1,
      isSalerBottom: false,
      isScroll: false,
      activeName: "all",
      activeAllData: "all",
      list: [],
      isLoading: false,
      pageSize: 10,
      curPage: 1,
      isBottom: false,

      listStaff: [],
      isLoadingDepart: false,
      curPageDepart: 1,
      isBottomDepart: false,
      totalStaff: 0,
      reLoadStaffList: false,

      aiList: [],
      abList: [],//雷达图 数值
      aiIsLoading: false,
      aiCurPage: 1,
      aiIsBottom: false,

      allData: {
        memberCount: 0,
        forwardNum: 0,
        followNum: 0,
        pv: 0,
        saveNum: 0,
        thumbsNum: 0
      },
      swCur: 0,
      ecInt: {
        // 将 lazyLoad 设为 true 后，需要手动初始化图表
        lazyLoad: true
      },
      interestData: {},
      pickNameInterest: "近7天",
      ecFunnel: {
        lazyLoad: true
      },
      dealData: {},
      pickNameDeal: "近7天",
      ecNewCust: {
        lazyLoad: true
      },
      newCustData: {},
      askCustData: {},
      followCustData: {},
      mallOrderData: {},
      pickerNameNewCust: "近7天",
      pickerNameAskCust: "近7天",
      pickerNameMallOrder: "近7天",
      pickerNameFollowCust: "近7天",
      ecActiveCust: {
        lazyLoad: true
      },
      ecActiveData: {},
      ecInteraction: {
        lazyLoad: true
      },
      ecInteractionData: {
        list: []
      },
      pickerArr: [
        {
          name: "近7天",
          key: "7",
        },
        {
          name: "近15天",
          key: "15",
        },
        {
          name: "近30天",
          key: "30",
        }
      ],
      pickerName: "近7天",
      ecAi: {
        lazyLoad: true
      },
      abilityData: {},

      empManageEnable: false,
      createCardEnable: false
    })
    this.onLoad();
  },
  queryAi(){// query ai analysis
    var ctx = this;
    if (ctx.data.aiIsLoading || ctx.data.aiIsBottom) {
      return;
    }
    ctx.setData({ aiIsLoading: true });
    wx.request({
      url: cf.config.pageDomain + "/applet/mobile/visitcard/dataprofile/abilityList",
      data: {
        cusmallToken: cusmallToken,
        department: ctx.data.identify,
        start: (ctx.data.aiCurPage - 1) * ctx.data.pageSize,
        limit: ctx.data.pageSize,
      },
      header: {
        'content-type': 'application/json'
      },
      success: function (res) {
        var data = res.data;
        if (data && 0 === data.ret) {
          var list = data.model.employeeList || [];
          var abList = data.model.abilityList || [];
          ctx.setData({
            aiList: ctx.data.aiList.concat(list),
            abList: ctx.data.abList.concat(abList),
          });
          if (data.model.total == ctx.data.aiList.length) {
            ctx.setData({
              aiIsBottom: true
            });
          }
          
        } else {
          wx.showToast({
            title: data.msg,
            icon: "none"
          })
        }
      },
      fail() {

      },
      complete() {
        ctx.setData({ aiIsLoading: false });
        // ctx.queryAbilityData();
        ctx.renderRadar();
      }
    });
    
    

  },
  

  renderRadar(){
    var ctx = this;
    var abList = ctx.data.abList;
    for (var i = 0; i < abList.length; i++){
       if (0 == i) {

         ctx["radarComponent"] = ctx.selectComponent('#mychart-ai');
         ctx.initCommEc("radarComponent", "setRadarOption", abList[i]);
       } else {
         ctx["radarComponent" + i] = ctx.selectComponent('#mychart-ai' + i);
         ctx.initCommEc("radarComponent" + i, "setRadarOptionNoneName", abList[i]);
       }
     }

  },
  toDetailRadar(e){
    var eId = e.currentTarget.dataset.eid;
    wx.navigateTo({
      url: './ai_detail?eId=' + eId,
    })
  },

  setRadarOption(chart, itemData) {
    let ctx = this;
    var option = {
      backgroundColor: "#ffffff",
      color: ["rgba(114, 172, 209,0.8)"],
      // tooltip: {},
      xAxis: {
        show: false
      },
      yAxis: {
        show: false
      },
      radar: {
        indicator: [{
          name: '获客能力值',
          max: 100
        },
        {
          name: '销售主动值',
          max: 100
        },
        {
          name: '官网推广值',
          max: 100
        },
        {
          name: '个人能力值',
          max: 100
        },
        {
          name: '客户互动值',
          max: 100
        },
        {
          name: '产品推广值',
          max: 100
        }
        ]
      },
      series: [{
        type: 'radar',
        data: [{
          value: [itemData.customerAbility,
            itemData.saleAbility,
            itemData.portalSpreadAbility,
            itemData.personalAbility,
            itemData.interactionAbility,
            itemData.productSpreadAbility

           ],
          areaStyle: {
            normal: {
              color: 'rgba(114, 172, 209, 1)'
            }
          }
        }
        ]
      }]
    };

    chart.setOption(option);
  },
  setRadarOptionNoneName(chart, itemData){
    let ctx = this;
    var option = {
      backgroundColor: "#ffffff",
      color: ["rgba(114, 172, 209,0.8)"],
      // tooltip: {},
      xAxis: {
        show: false
      },
      yAxis: {
        show: false
      },
      radar: {
        // shape: 'circle',
        indicator: [{name: '',max: 100},
        {name: '', max: 100 },
        { name: '', max: 100 },
        { name: '', max: 100 },
        { name: '', max: 100 },
        { name: '', max: 100 }
        ]
      },
      series: [{
        type: 'radar',
        data: [{
          value: [itemData.customerAbility,
          itemData.saleAbility,
          itemData.portalSpreadAbility,
          itemData.personalAbility,
          itemData.interactionAbility,
          itemData.productSpreadAbility

          ],
          areaStyle: {
            normal: {
              color: 'rgba(114, 172, 209, 1)'
            }
          }
        }
        ]
      }]
    };

    chart.setOption(option);
  },

  initCommEc(domName, optionName, params) {
    let ctx = this;
    this[domName].init((canvas, width, height) => {
      // 获取组件的 canvas、width、height 后的回调函数
      // 在这里初始化图表
      const chart = echarts.init(canvas, null, {
        width: width,
        height: height
      });
      ctx[optionName](chart, params);

      // 将图表实例绑定到 this 上，可以在其他成员函数（如 dispose）中访问
      this.chart = chart;

      // 注意这里一定要返回 chart 实例，否则会影响事件处理等
      return chart;
    });
  },
  interest(day) {//ai分析 兴趣统计
    var ctx = this;
    var submitData = {
      cusmallToken: cusmallToken,
      department: ctx.data.identify,
      countAll: true,
    }
    if (ctx.data.identify){
      submitData.countAll = false;
    }
    if (day) {
      submitData.startDate = util.formatDate(new Date(Date.now() - (day * 86400000)));
      submitData.endDate = util.formatDate(new Date(Date.now() - (1 * 86400000)));
    }
    wx.request({
      url: cf.config.pageDomain + "/applet/mobile/visitcard/dataprofile/interest",
      data: submitData,
      header: {
        'content-type': 'application/json'
      },
      success: function (res) {
        var data = res.data;
        if (data && 0 === data.ret) {
          ctx.setData({
            interestData: {
              toCompanyPerD: data.model.toCompanyPerD,
              toMePerD: data.model.toMePerD,
              toProductPerD: data.model.toProductPerD
            }
          });
          ctx.initCommEc("interestComponent","setInterestOption");
        } else {
          ctx.setData({
            interestData: {
              toCompanyPerD: 33.33,
              toMePerD: 33.33,
              toProductPerD: 33.33
            }
          });
          ctx.initCommEc("interestComponent", "setInterestOption");
        }
      },
      fail() {

      },
      complete() {
      }
    });
  },
  setInterestOption(chart) {

    let ctx = this;
    var option = {
      color: ["#FF5722", "#FF9800", "#00BCD4"],
      legend: {
        itemWidth: 10,
        itemHeight: 10,
        selectedMode: false,
        orient: 'horizontal',
        bottom: 40,
        data: ["对我感兴趣", "对产品感兴趣", "对公司感兴趣"]
      },
      series: [{
        label: {
          normal: {
            fontSize: 14,
            formatter: "{d}%",
            color: "#000000"
          }
        },
        type: 'pie',
        center: ['50%', '40%'],
        radius: [0, '60%'],
        data: [{
          value: ctx.data.interestData.toMePerD,
          name: '对我感兴趣'
        }, {
            value: ctx.data.interestData.toProductPerD,
          name: '对产品感兴趣'
        }, {
            value: ctx.data.interestData.toCompanyPerD,
          name: '对公司感兴趣'
        },
        ],

        itemStyle: {
          emphasis: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 2, 2, 0.3)'
          }
        }
      }]
    };

    chart.setOption(option);
  },
  dealPer(day){
    var ctx = this;
    
    var submitData ={
      cusmallToken: cusmallToken,
      department: ctx.data.identify,
      countAll: true,
    }
    if (ctx.data.identify) {
      submitData.countAll = false;
    }
    if (day){
      submitData.startDate = util.formatDate(new Date(Date.now() - (day * 86400000)));
      submitData.endDate = util.formatDate(new Date(Date.now() - (1 * 86400000)));
    }
    wx.request({
      url: cf.config.pageDomain + "/applet/mobile/visitcard/dataprofile/bargainFunnel",
      data: submitData,
      header: {
        'content-type': 'application/json'
      },
      success: function (res) {
        var data = res.data;
        if (data && 0 === data.ret) {
          ctx.setData({
            dealData: data.model
          })
          // ctx.initCommEc("dealComponent", "setDealOption");
        } else {
          
        }
      },
      fail() {

      },
      complete() {
      }
    });
    
  },
  setDealOption(chart){
    let ctx = this;
    var option = {
      backgroundColor: "#ffffff",
      color: ["#23bda5", "#f9bb40", "#ff7441", "#f76162"],
      // tooltip: {
      //   trigger: 'item',
      //   formatter: "{a} <br/>{b} : {c}%"
      // },
      legend: {
        selectedMode: false,
        itemWidth: 10,
        itemHeight: 10,
        bottom:"15%;",
        borderRadius:100,
        data: ['≤50%', '≤80%', '≤99%', '≤100%']
      },
      calculable: true,
      series: [
        {
          top: 0,

          name: '',
          type: 'funnel',
          left: '10%',
          width: '80%',
          height:"80%",
          gap: 10,
          minSize: "30%",
          maxSize: "90%",
          label: {
            
            normal: {
                show: false,
              color: '#353535',
              position: 'left',

            },
            emphasis: {
              position: 'left',
              formatter: '{c}%'
            }
          },
          data: ctx.data.dealData
        },
        {
          name: '',
          type: 'funnel',
          top: 0,
          gap: 10,
          label: {
            normal: {
              position: 'inside',
              formatter: '{c}',
              textStyle: {
                color: '#fff'
              }
            }

          },
          itemStyle: {
            normal: {
              color: 'transparent',
              borderWidth: 0,
              opacity: 0
            }
          },
          data: ctx.data.dealData
        }
        
        
      ]
    };

    chart.setOption(option);
  },
  newCust(day) {
    var ctx = this;
    ctx.dataTrendHandle(day, 1, function(data){
      if (data && 0 === data.ret) {
        var activeNum = [];
        var activeDay = [];
        for (let item of data.model.list) {
          activeNum.push(item.memberCount);
          activeDay.push(item.day.substring(5));
        }
        ctx.setData({
          newCustData: {
            activeNum: activeNum.reverse(),
            activeDay: activeDay.reverse()
          }
        });
        ctx.initCommEc("newCustComponent", "setNewCustOption");
      } else {
        wx.showToast({
          title: data.msg,
          icon: "none"
        })
      }
    });
    
  },
  askCust(day){
    var ctx = this;
    ctx.dataTrendHandle(day, 6, function (data) {
      if (data && 0 === data.ret) {
        var activeNum = [];
        var activeDay = [];
        for (let item of data.model.list) {
          activeNum.push(item.consultNum);
          activeDay.push(item.day.substring(5));
        }
        ctx.setData({
          askCustData: {
            activeNum: activeNum.reverse(),
            activeDay: activeDay.reverse()
          }
        });
        ctx.initCommEc("askCustComponent", "setAskCustOption");
      } else {
        wx.showToast({
          title: data.msg,
          icon: "none"
        })
      }
    });
  },
  mallOrder(day){
    var ctx = this;
    ctx.dataTrendHandle(day, 8, function (data) {
      if (data && 0 === data.ret) {
        var totalAmount = [];
        var orderCount = [];
        var activeDay = [];
        for (let item of data.model.list) {
          totalAmount.push((item.totalAmount/100).toFixed(2));
          orderCount.push(item.orderCount);
          activeDay.push(item.day.substring(5));
        }
        ctx.setData({
          mallOrderData: {
            totalAmount: totalAmount.reverse(),
            orderCount: orderCount.reverse(),
            activeDay: activeDay.reverse()
          }
        });
        ctx.initCommEc("mallComponent", "setMallOrderOption");
      } else {
        wx.showToast({
          title: data.msg,
          icon: "none"
        })
      }
    });
  },
  followCust(day){
    var ctx = this;
    ctx.dataTrendHandle(day, 7, function (data) {
      if (data && 0 === data.ret) {
        var activeNum = [];
        var activeDay = [];
        for (let item of data.model.list) {
          activeNum.push(item.followNum);
          activeDay.push(item.day.substring(5));
        }
        ctx.setData({
          followCustData: {
            activeNum: activeNum.reverse(),
            activeDay: activeDay.reverse()
          }
        });
        ctx.initCommEc("followCustComponent", "setFollowCustOption");
      } else {
        wx.showToast({
          title: data.msg,
          icon: "none"
        })
      }
    });
  },
  /**
   * day 天数
   * dataType 查询的类型 1 新增客户数 6 咨询人数 7 跟进客户数
   */
  dataTrendHandle(day, dataType, cb){
    var ctx = this;
    wx.request({
      url: cf.config.pageDomain + "/applet/mobile/visitcard/dataprofile/dataTrend",
      data: {
        cusmallToken: cusmallToken,
        department: ctx.data.identify,
        dayNum: day,
        "type": dataType,
      },
      header: {
        'content-type': 'application/json'
      },
      success: function (res) {
        var data = res.data;
        cb && cb(data);
        
      },
      fail() {

      },
      complete() {
      }
    });
  },
  otherCharts(){
    var ctx = this;
    ctx.initCommEc("askCustComponent", "setOtherChartsOption");
    ctx.initCommEc("followCustComponent", "setOtherChartsOption");
    ctx.initCommEc("mallComponent", "setOtherChartsOption");
  },
  setNewCustOption(chart){
    let ctx = this;
    var dateList = [];
    var nowDate = Date.now(),mDate;
    for(let i = 0; i < 7; i++){
      mDate = new Date(nowDate - (i * 86400000));
      dateList.push(util.numAddPreZero((mDate.getMonth() + 1)) + "-" + util.numAddPreZero(mDate.getDate()));
    }
    dateList.reverse();
    var option = {
      title: { text: '', left: 'center' },
      color: ["#37A2DA"],
      grid: { top: "5%", containLabel: true },
      xAxis: {
        type: 'category',
        boundaryGap: false,
        data: ctx.data.newCustData.activeDay,
      },
      yAxis: {
        x: 'center',
        type: 'value',
        splitLine: {
          lineStyle: {
            type: 'solid'
          }
        },
        min: 0
      },
      series: [{
        top: 0,
        name:"新增客户数",
        type: 'line',
        smooth: true,
        data: ctx.data.newCustData.activeNum
      }]
    };

    chart.setOption(option);
  },
  setAskCustOption(chart){
    let ctx = this;
    var dateList = [];
    var nowDate = Date.now(),mDate;
    for(let i = 0; i < 7; i++){
      mDate = new Date(nowDate - (i * 86400000));
      dateList.push(util.numAddPreZero((mDate.getMonth() + 1)) + "-" + util.numAddPreZero(mDate.getDate()));
    }
    dateList.reverse();
    var option = {
      title: { text: '', left: 'center' },
      color: ["#37A2DA"],
      grid: { top: "5%", containLabel: true },
      xAxis: {
        type: 'category',
        boundaryGap: false,
        data: ctx.data.askCustData.activeDay,
      },
      yAxis: {
        x: 'center',
        type: 'value',
        splitLine: {
          lineStyle: {
            type: 'solid'
          }
        },
        min: 0
      },
      series: [{
        top: 0,
        name:"咨询用户数",
        type: 'line',
        smooth: true,
        data: ctx.data.askCustData.activeNum
      }]
    };

    chart.setOption(option);
  },
  setFollowCustOption(chart){
    let ctx = this;
    var dateList = [];
    var nowDate = Date.now(),mDate;
    for(let i = 0; i < 7; i++){
      mDate = new Date(nowDate - (i * 86400000));
      dateList.push(util.numAddPreZero((mDate.getMonth() + 1)) + "-" + util.numAddPreZero(mDate.getDate()));
    }
    dateList.reverse();
    var option = {
      title: { text: '', left: 'center' },
      color: ["#37A2DA"],
      grid: { top: "5%", containLabel: true },
      xAxis: {
        type: 'category',
        boundaryGap: false,
        data: ctx.data.followCustData.activeDay,
      },
      yAxis: {
        x: 'center',
        type: 'value',
        splitLine: {
          lineStyle: {
            type: 'solid'
          }
        },
        min: 0
      },
      series: [{
        top: 0,
        name:"咨询用户数",
        type: 'line',
        smooth: true,
        data: ctx.data.followCustData.activeNum
      }]
    };

    chart.setOption(option);
  },
  setMallOrderOption(chart){
    let ctx = this;
    var dateList = [];
    var nowDate = Date.now(), mDate;
    for (let i = 0; i < 7; i++) {
      mDate = new Date(nowDate - (i * 86400000));
      dateList.push(util.numAddPreZero((mDate.getMonth() + 1)) + "-" + util.numAddPreZero(mDate.getDate()));
    }
    dateList.reverse();
    var option = {
      title: { text: '', left: 'center' },
      color: ["#37A2DA","#d14a61"],
      grid: { top: "10%", containLabel: true },
      legend: {
        data: ['收益', '订单数'],
        top: 0,
        left: 'center',
        z: 100
      },
      // center: ['80%', '40%'],
      xAxis: {
        type: 'category',
        boundaryGap: false,
        data: ctx.data.mallOrderData.activeDay,
      },
      yAxis: [{
        x: 'center',
        type: 'value',
        splitLine: {
          lineStyle: {
            type: 'solid'
          }
        },
        min: 0
      },{
          type: 'value',
          splitLine: {
            lineStyle: {
              type: 'solid'
            }
          },
          min: 0
        }],
      series: [{
        top: 0,
        name: "收益",
        type: 'line',
        smooth: true,
        data: ctx.data.mallOrderData.totalAmount
      },
        {
          top: 0,
          name: "订单数",
          type: 'line',
          smooth: true,
          // itemStyle: {
          //   normal: {
          //     color: "#d14a61"
          //   }
          // },
          data: ctx.data.mallOrderData.orderCount
        }
      ]
    };

    chart.setOption(option);
  },
  setOtherChartsOption(chart){
    let ctx = this;
    var dateList = [];
    var nowDate = Date.now(), mDate;
    for (let i = 0; i < 7; i++) {
      mDate = new Date(nowDate - (i * 86400000));
      dateList.push(util.numAddPreZero((mDate.getMonth() + 1)) + "-" + util.numAddPreZero(mDate.getDate()));
    }
    dateList.reverse();
    var option = {
      title: {
        text: '',
        left: 'center'
      },
      color: ["#37A2DA"],
      // tooltip: {
      //   show: true,
      //   trigger: 'axis'
      // },
      grid: {
        top: "5%",
        containLabel: true
      },

      xAxis: {
        type: 'category',
        boundaryGap: false,
        data: dateList,
      },
      yAxis: {
        x: 'center',
        type: 'value',
        splitLine: {
          lineStyle: {
            type: 'solid'
          }
        },
        min: 0
      },
      series: [{
        top: 0,
        type: 'line',
        smooth: true,
        data: [0, 0, 0, 0, 0, 0, 0]
      }]
    };

    chart.setOption(option);
  },
  activeCust(day){
    var ctx = this;
    wx.request({
      url: cf.config.pageDomain + "/applet/mobile/visitcard/dataprofile/bossActiveTrend",
      data: {
        cusmallToken: cusmallToken,
        department: ctx.data.identify,
        dayNum: day
      },
      header: {
        'content-type': 'application/json'
      },
      success: function (res) {
        var data = res.data;
        if (data && 0 === data.ret) {
          var activeNum = [];
          var activeDay = [];
          for (let item of data.model.list) {
            activeNum.push(item.activeNum);
            activeDay.push(item.day.substring(5));
          }
          ctx.setData({
            ecActiveData: {
              activeNum: activeNum.reverse(),
              activeDay: activeDay.reverse()
            }
          });
          ctx.initCommEc("activeCustComponent", "setActiveCustOption");
        } else {

        }
      },
      fail() {

      },
      complete() {
      }
    });
  },
  setActiveCustOption(chart){
    let ctx = this;
    var option = {
      title: {
        text: '',
        left: 'center'
      },
      // tooltip: {
      //   show: true,
      //   trigger: 'axis'
      // },
      color: ["#37A2DA"],

      grid: {
        top:"5%",
        containLabel: true
      },

      xAxis: {
        type: 'category',
        boundaryGap: false,
        data: ctx.data.ecActiveData.activeDay,
      },
      yAxis: {
        x: 'center',
        type: 'value',
        splitLine: {
          lineStyle: {
            type: 'solid'
          }
        },
        min: 0
      },
      series: [{
        name: " 活跃度",
        type: 'line',
        smooth: true,
        data: ctx.data.ecActiveData.activeNum
      }]
    };

    chart.setOption(option);
  },

  interaction(){
    var ctx = this;
    wx.request({
      url: cf.config.pageDomain + "/applet/mobile/visitcard/dataprofile/bossInteraction",
      data: {
        cusmallToken: cusmallToken,
        department: ctx.data.identify
        // department:""
      },
      header: {
        'content-type': 'application/json'
      },
      success: function (res) {
        var data = res.data;
        if (data && 0 === data.ret) {
          ctx.setData({
            ecInteractionData: {
              list: [data.model.thumbs, 
              data.model.comment, data.model.askGoods, data.model.forward, data.model.call, data.model.save, data.model.addMemory]
            }
          })
          ctx.initCommEc("interactionComponent", "setInteractionOption");
        } else {

        }
      },
      fail() {
      },
      complete() {
      }
    });
  },
  setInteractionOption(chart) {
    let ctx = this;
    var option = {
      title: {
        text: '',
        left: 'center'
      },
      // tooltip:{
      //   formatter: '{b}：{c}',
      //   show: true,
      //   trigger: 'axis'
      // },
      grid: {
        top: "5%",
        containLabel: true
      },

      xAxis: {
        type: 'value',
        axisLine: {
          lineStyle: {
            color: '#999'
          }
        },
        axisLabel: {
          color: '#666'
        }
      },
      yAxis:
        {
          type: 'category',
          axisTick: { show: false },
          data: ['点赞', '评论', '咨询产品', '转发', '拨打电话', '保存电话', '印象标签'],
          axisLine: {
            lineStyle: {
              color: '#999'
            }
          },
          axisLabel: {
            color: '#666'
          }
        }
      ,
      series: [{
        smooth: true,
        type: 'bar',
        label: {
          normal: {
            show: true,
            position: 'inside'
          }
        },
        data: ctx.data.ecInteractionData.list,
        itemStyle: {
          normal: {
            color: function (params) {
              var colorList = ["#FF5722", 
              "#00BCD4", "#9E9E9E", "#616161", "#795548", "#009688", "#FF9800"];
              return colorList[params.dataIndex];
            }
          }
          // emphasis: {
          //   color: '#37a2da'
          // }
        }
      }]
    };

    chart.setOption(option);
  },
  

  bindPickerChange(e){
    let ctx = this;
    let day = this.data.pickerArr[e.detail.value].key;
    let name = this.data.pickerArr[e.detail.value].name;
    let target = e.currentTarget.dataset.target;
    
    if("active" == target){
      ctx.activeCust(day);
      ctx.setData({
        pickerName: name
      });
    } else if ("newcust" == target){
      ctx.newCust(day);
      ctx.setData({
        pickerNameNewCust: name
      });
    } else if ("askcust" == target) {
      ctx.askCust(day);
      ctx.setData({
        pickerNameAskCust: name
      });
    } else if ("mallorder" == target){
      ctx.mallOrder(day);
      ctx.setData({
        pickerNameMallOrder: name
      });
    } else if ("followcust" == target) {
      ctx.followCust(day);
      ctx.setData({
        pickerNameFollowCust: name
      });
    } else if ("interest" == target){
      ctx.interest(day);
      ctx.setData({
        pickNameInterest: name
      });
    } else if ("dealper" == target){
      ctx.dealPer(day);
      ctx.setData({
        pickNameDeal: name
      });
    }
  },
  findEmployeePrivilege(){
    var ctx = this;
    wx.request({
      url: cf.config.pageDomain + "/applet/mobile/visitcard/employee/findEmployeePrivilege",
      data: {
        cusmallToken: cusmallToken
      },
      header: {
        'content-type': 'application/json'
      },
      success: function (res) {
        var data = res.data;
        if (data && 0 === data.ret) {
          var employeePrivilege = data.model.employeePrivilege  || {};
          var createCardEnable = employeePrivilege.createCardEnable;
          ctx.setData({
            createCardEnable: createCardEnable,
            empManageEnable: employeePrivilege.empManageEnable,
            restCard: employeePrivilege.restCard || 0,
          });
          ctx.findDepartmentEmployees();
        } else {
          wx.showToast({
            title: data.msg,
            icon:"none"
          })
        }
      },
      fail() {

      },
      complete() {
      }
    });
  },
  toCustomList(e){
    var eId = e.currentTarget.dataset.eid;
    wx.navigateTo({
      url: './custom_list?eId=' + eId,
    });
  },
  addStaff(){//添加员工
    var ctx = this;
    if (0 < ctx.data.restCard){
      wx.navigateTo({
        url: './add_staff',
      });
      
    }else{
      wx.showModal({
        title: '提示',
        content: '你的员工名额已不足，请联系供应商增加配额',
        showCancel:false,
        confirmText:"知道了",
        success(res) {
          if (res.confirm) {
            console.log('用户点击确定')
          } else if (res.cancel) {
            console.log('用户点击取消')
          }
        }
      })
    }
    
  },
  staffActivationCode(){
    wx.navigateTo({
      url: './staff_act_code',
    })
  },
  //员工管理
  findDepartmentEmployees(){
    var ctx = this;
    if (ctx.data.isLoadingDepart || ctx.data.isBottomDepart) {
      return;
    }
    ctx.setData({ isLoadingDepart: true });
    wx.request({
      url: cf.config.pageDomain + "/applet/mobile/visitcard/employee/findDepartmentEmployees",
      data: {
        cusmallToken: cusmallToken,
        start: (ctx.data.curPageDepart - 1) * ctx.data.pageSize,
        limit: ctx.data.pageSize,
        identify: ctx.data.identify,
        isWxbind: false//是否只查询微信绑定的 不传或传false则忽略绑定条件
      },
      header: {
        'content-type': 'application/json'
      },
      success: function (res) {
        var data = res.data;
        if (data && 0 === data.ret) {
          console.log(data)
          var list = data.model.list || [];
          list.map(function(item){
            item.createTimeFormat = util.formatTime(new Date(item.createTime));
          })
          ctx.setData({
            listStaff: ctx.data.listStaff.concat(list),
            totalStaff: data.model.total
          });
          if (data.model.total == ctx.data.listStaff.length) {
            ctx.setData({
              isBottomDepart: true
            });
          }
        } else {
          wx.showToast({
            title: data.msg,
            icon: "none"
          })
        }
      },
      fail() {

      },
      complete() {
        ctx.setData({ isLoadingDepart: false });
      }
    });
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    var  ctx = this;
    
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var ctx = this;
    if (ctx.data.reLoadStaffList){
      ctx.setData({ 
        listStaff: [],
        isLoadingDepart: false,
        curPageDepart: 1,
        isBottomDepart: false
      });
      ctx.findEmployeePrivilege();
      ctx.findDepartmentEmployees();
      ctx.setData({
        reLoadStaffList: false
      });
    }
  },
  changeDep:function(){
    wx.navigateTo({
      url: './selDepartment?saveKey=identify,name',
    })
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
  
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
  
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
  
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    let ctx = this;
    if (ctx.data.isLoading || ctx.data.isLoadingDepart || "all" == ctx.data.activeName || ctx.data.aiIsLoading ) {
      return;
    }
    if ("rank" == ctx.data.activeName){
      ctx.setData({ curPage: ctx.data.curPage + 1 });
      ctx.queryCustomerRank(1);
    } else if ("ai" == ctx.data.activeName){
      ctx.setData({ aiCurPage: ctx.data.aiCurPage + 1 });
      ctx.queryAi();
    } else if ("search" == ctx.data.activeName) {
    	ctx.setData({isScroll: true});
      ctx.searchSales();
    } else if ("staff" == ctx.data.activeName){
      ctx.setData({ curPageDepart: ctx.data.curPageDepart + 1 });
      ctx.findDepartmentEmployees();
    } 
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
  
  }
}))